package com.gxa.modules.service.impl;

import com.gxa.common.constant.Constants;
import com.gxa.common.exception.LcException;
import com.gxa.common.utils.GenerateSequenceUtil;
import com.gxa.common.vo.PageRecv;
import com.gxa.common.vo.PageResult;
import com.gxa.common.vo.ResultVo;
import com.gxa.modules.mapper.ContractMapper;
import com.gxa.modules.pojo.Contract;
import com.gxa.modules.pojo.LoanSearch;
import com.gxa.modules.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: microloans_system
 * @description: 合同业务类
 * @author: LC
 * @create: 2021-12-28 16:15
 */

@Service
public class ContractServiceImpl implements ContractService{

    @Autowired(required = false)
    ContractMapper contractMapper;

    @Value("${fileUploadPath}")
    String fileUploadPath;

    @Override
    public ResultVo getContractInfo(PageRecv<LoanSearch> loanSearchPageRecv) {
        ResultVo r=new ResultVo();
        //查询终审，放款审批状态的贷款
        List<Integer> states=new ArrayList<>();
        states.add(Constants.LOAN_THIRD_PASSING);
        states.add(Constants.LOAN_GIVE_REVIEW);
        loanSearchPageRecv.getData().setLoan_state(states);

        List<Contract> contractList=contractMapper.queryContractPageByCondition(loanSearchPageRecv);
        PageResult pageResult=new PageResult();
        long count=contractMapper.countContractPageByCondition(loanSearchPageRecv);
        pageResult.setTotalSize(count);
        pageResult.setList(contractList);
        r.setCode(200);
        r.setData(pageResult);
        return r;
    }


    @Override
    public ResultVo uploadFile(MultipartFile file) {
        ResultVo r=new ResultVo();
        if(file.isEmpty()){
            throw new LcException(400,"未选中文件，请选择文件后上传！");
        }

        String name=file.getOriginalFilename();
        String suffix=name.substring(name.lastIndexOf("."));
        if((!suffix.equals(".doc")&& !suffix.equals(".docx")&& !suffix.equals(".pdf"))){
            throw new LcException(400,"只能上传word/pdf格式的文件！");
        }

        if((file.getSize()>2*1024*1024)){
            throw new LcException(400,"文件大小不能超过2M！");
        }

        String no=GenerateSequenceUtil.generateSequenceNo();
        String newName= no+suffix;
        String path=fileUploadPath+ File.separator+newName;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
            throw new LcException(500,"文件上传失败，请联系管理员！");
        }
        Contract contract=new Contract();
        contract.setCon_no(no);
        contract.setCon_url(newName);
        r.setCode(200);
        r.setData(contract);
        return r;
    }

    @Override
    public ResultVo addContract(Contract contract) {
        ResultVo r=new ResultVo();

        //删除原有的合同
        int delResult=contractMapper.updateContractStatus(Constants.CONTRACT_DEL,contract.getId());
        if(delResult<=0){
            throw new LcException(500,"删除原有合同失败，请联系管理员！");
        }

        //添加新的合同
        int result=contractMapper.insertContract(contract);
        if(result<=0){
            throw new LcException(500,"上传合同失败，请联系管理员！");
        }
        //若合同生成成功，设置成放款审批状态
        int statusResult=contractMapper.updateLoanState(contract.getLoan_id(),Constants.LOAN_GIVE_REVIEW);
        if(statusResult<=0){
            throw new LcException(500,"更新放款审批状态失败，请联系管理员！");
        }
        r.setCode(200);
        r.setMsg("上传成功！");
        return r;
    }

    @Override
    public void downloadFile(String fileUrl, HttpServletResponse response) {
        File file=new File(fileUploadPath+File.separator+fileUrl);
        if(!file.exists()){
            System.out.println("不存在");
        }

        try {
            OutputStream os=response.getOutputStream();
            FileInputStream fis=new FileInputStream(file);
            //设置相应类型application/octet-stream
            response.setContentType("application/x-msdownload");
            //设置头信息
            response.setHeader("Content-Disposition", "attachment;fileName=\"" + file.getName() + "\"");
            byte[] temp=new byte[1024*2];
            int len;
            while(-1!=(len=fis.read(temp))){
                os.write(temp,0 ,len);
            }
            os.flush();
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void previewFile(String fileUrl, HttpServletResponse response) {
        File file=new File(fileUploadPath+File.separator+fileUrl);
        if(!file.exists()){
            System.out.println("不存在");
        }

        try {
            OutputStream os=response.getOutputStream();
            FileInputStream fis=new FileInputStream(file);
            byte[] temp=new byte[1024*2];
            int len;
            while(-1!=(len=fis.read(temp))){
                os.write(temp,0 ,len);
            }
            os.flush();
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}